package com.acxy.ants.core.plugin.cron4j;

import com.acxy.ants.core.Plugin;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author MrShun
 * @version 1.0
 * @Date 2017-06-16
 */
public class Cron4jPlugin implements Plugin {

    private ConcurrentHashMap<String, Task> tasks = new ConcurrentHashMap();

    @Override
    public boolean start() {
        for(Map.Entry<String, Task> entry: tasks.entrySet()){
            Timer timer = new Timer();
            Task t = entry.getValue();
            TaskKit.set(t.getName(), timer);
            if(t.getTime() != null && t.getDelay() == null && t.getPeriod() == null)
                timer.schedule(t, t.getTime());
            else if(t.getDelay() != null && t.getTime() == null && t.getPeriod() == null)
                timer.schedule(t, t.getDelay());
            else if(t.getTime() != null && t.getPeriod() != null && t.getDelay() == null)
                timer.schedule(t, t.getTime(), t.getPeriod());
            else if(t.getPeriod() != null && t.getDelay() != null && t.getTime() == null)
                timer.schedule(t, t.getDelay(), t.getPeriod());
        }
        return true;
    }

    @Override
    public boolean destroy() {
        TaskKit.stop();
        return true;
    }

    public void add(Task task){
        tasks.put(task.getName(), task);
    }
}
